package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;
    @Scheduled(cron = "0 00 8 * * ?")
    public void processTimeOutOrder(){
        log.info("定时处理超时订单,{}", LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        //select * from orders where status = 2 and order_time < (当前时间-15分钟)
        List<Orders> orders=orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT,time);
        if(orders!=null&&orders.size()>0){
            for (Orders order : orders) {
                order.setStatus(Orders.CANCELLED);
                order.setCancelTime(LocalDateTime.now());
                order.setCancelReason("订单超时自动取消");
                orderMapper.update(order);
            }
        }
    }


    /**
     * 处理一直处于派送中的订单
     */
    @Scheduled(cron = "0 00 8 * * ?")
    public void processDeliveryOrder(){
        log.info("处理一直处于派送中的订单{}",LocalDateTime.now());
        List<Orders> orders = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().plusHours(-1));
        if(orders!=null&&orders.size()>0){
            for (Orders order : orders) {
                order.setStatus(Orders.COMPLETED);
                order.setCancelTime(LocalDateTime.now());
                order.setCancelReason("订单一直处于派送中");
                orderMapper.update(order);
            }
        }
    }
}
